package nbcp.base.utils

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
import java.nio.charset.Charset

object AESUtils {
    // 加密
    @Throws(Exception::class)
    fun encrypt(sSrc: String, sKey: String): String {
        if (sKey == null) {
            print("Key为空null")
            return ""
        }
        // 判断Key是否为16位
        if (sKey.length != 16) {
            print("Key长度不是16位")
            return ""
        }
        val raw = sKey.toByteArray(charset("utf-8"))
        val skeySpec = SecretKeySpec(raw, "AES")
        val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
        val encrypted = cipher.doFinal(sSrc.toByteArray(charset("utf-8")))

        return Base64().encodeToString(encrypted)//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    @Throws(Exception::class)
    fun decrypt(sSrc: String, sKey: String): String {
        // 判断Key是否正确
        if (sKey == null) {
            print("Key为空null")
            return ""
        }
        // 判断Key是否为16位
        if (sKey.length != 16) {
            print("Key长度不是16位")
            return ""
        }
        val raw = sKey.toByteArray(charset("utf-8"))
        val skeySpec = SecretKeySpec(raw, "AES")
        val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, skeySpec)
        val encrypted1 = Base64().decode(sSrc)//先用base64解密

        val original = cipher.doFinal(encrypted1)
        return String(original, Charset.forName("utf-8"))
    }
}